using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service.Mp;

/// <summary>
/// 小程序房间详情相关接口
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class MpRoomService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly UserManager _userManager;

	private readonly SqlSugarRepository<Room> _rep;

	private readonly SqlSugarRepository<PowerConsumptionRecord> _record;

	public MpRoomService(UserManager userManager, SqlSugarRepository<Room> rep, SqlSugarRepository<PowerConsumptionRecord> record)
	{
		_userManager = userManager;
		_rep = rep;
		_record = record;
	}

	/// <summary>
	/// 获取业主所有房间
	/// </summary>
	/// <returns></returns>
	[HttpGet("/mproom/getownerrooms")]
	public async Task<dynamic> GetOwnerRooms()
	{
		List<OwnerRoomsDto> rooms = await (from u in _rep.AsQueryable()
			where u.OwnerId == (long?)_userManager.UserId
			select new OwnerRoomsDto
			{
				Name = u.Name,
				Area = u.Area,
				Balance = u.Balance,
				Id = u.Id,
				BuildingId = u.BuildingId,
				BuildingName = from b in SqlFunc.Subqueryable<Building>()
					where b.Id == u.BuildingId
					select b.Name
			}).ToListAsync();
		foreach (OwnerRoomsDto item in rooms)
		{
			item.Balance = Math.Round(item.Balance, 2);
		}
		return rooms;
	}

	/// <summary>
	/// 获取房间的日环比，周同比，本月费用
	/// </summary>
	/// <param name="id"></param>
	/// <returns></returns>
	[HttpGet("/mproom/getroomfeerate")]
	public async Task<dynamic> GetRoomFeeRate([FromQuery] long id)
	{
		DateTime date = DateTime.Today;
		DateTime yesterday = date.AddDays(-1.0);
		DateTime beforYesterday = date.AddDays(-2.0);
		DateTime sevenDay = date.AddDays(-7.0);
		DateTime fourteenDay = date.AddDays(-14.0);
		decimal yesterdayFee = await (from u in _record.AsQueryable()
			where u.RoomId == (long?)id && u.CreateTime < date && u.CreateTime >= yesterday
			select u).SumAsync((PowerConsumptionRecord u) => u.CombinedActiveTotalElectricEnergyDifference);
		decimal beforYesterdayFee = await (from u in _record.AsQueryable()
			where u.RoomId == (long?)id && u.CreateTime < yesterday && u.CreateTime >= beforYesterday
			select u).SumAsync((PowerConsumptionRecord u) => u.CombinedActiveTotalElectricEnergyDifference);
		string dayOnMonthRatio = "不适用";
		if (beforYesterdayFee > 0m)
		{
			dayOnMonthRatio = Math.Round((yesterdayFee - beforYesterdayFee) / beforYesterdayFee * 100m, 2) + "%";
		}
		decimal sevendayFee = await (from u in _record.AsQueryable()
			where u.RoomId == (long?)id && u.CreateTime < date && u.CreateTime >= sevenDay
			select u).SumAsync((PowerConsumptionRecord u) => u.CombinedActiveTotalElectricEnergyDifference);
		decimal fourteendayFee = await (from u in _record.AsQueryable()
			where u.RoomId == (long?)id && u.CreateTime < sevenDay && u.CreateTime >= fourteenDay
			select u).SumAsync((PowerConsumptionRecord u) => u.CombinedActiveTotalElectricEnergyDifference);
		string weeklyYoY = "不适用";
		if (fourteendayFee > 0m)
		{
			weeklyYoY = Math.Round(sevendayFee / fourteendayFee * 100m, 2) + "%";
		}
		DateTime monthbegin = DateTime.Parse(date.ToString("yyyy-MM-01"));
		DateTime now = DateTime.Now;
		decimal currentMonthFee = (await (from u in _record.AsQueryable()
			where u.RoomId == (long?)id && u.CreateTime < now && u.CreateTime >= monthbegin && u.Amount != null
			select u).SumAsync((PowerConsumptionRecord u) => u.Amount)).GetValueOrDefault();
		return new
		{
			weeklyYoY = weeklyYoY,
			currentMonthFee = Math.Round(currentMonthFee, 2),
			dayOnMonthRatio = dayOnMonthRatio
		};
	}

	[HttpGet("/mproom/getmeterpower")]
	public async Task<dynamic> GetMeterPower([FromQuery] string sn)
	{
		DateTime monthbegin = DateTime.Parse(DateTime.Today.ToString("yyyy-MM-01"));
		DateTime now = DateTime.Now;
		return await (from u in _record.AsQueryable()
			where u.Sn == sn && u.CreateTime < now && u.CreateTime >= monthbegin
			select u).SumAsync((PowerConsumptionRecord u) => u.CombinedActiveTotalElectricEnergyDifference);
	}
}
